namespace Doc.CodeSamples.Tests
{
    using Unity.Entities;
    using Unity.Transforms;
    using Unity.Burst;
    using Unity.Mathematics;

    [BurstCompile]
    public partial struct SpawnerSystem : ISystem
    {
        public void OnCreate(ref SystemState state) { }

        public void OnDestroy(ref SystemState state) { }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var ecb = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>().
                CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter();
            new ProcessSpawnerJob
            {
                Ecb = ecb,
            }.ScheduleParallel();
        }
    }

    [BurstCompile]
    public partial struct ProcessSpawnerJob : IJobEntity
    {
        public EntityCommandBuffer.ParallelWriter Ecb;
        private void Execute([ChunkIndexInQuery] int chunkIndex, ref Spawner spawner)
        {
            if (spawner.count > 0)
            {
                //var random = new System.Random();
                //var x = random.Next(0, 100);
                //var y = random.Next(0, 100);
                //var z = random.Next(0, 100);
                Entity newEntity = Ecb.Instantiate(chunkIndex, spawner.Prefab);
                Ecb.SetComponent(chunkIndex, newEntity, new LocalTransform()
                {
                    Position = spawner.position,
                    Scale = spawner.scaleDelta,
                    Rotation = quaternion.LookRotation(spawner.forward, spawner.up)
                });
                Ecb.AddComponent(chunkIndex, newEntity, new PostTransformMatrix()
                {
                    Value = float4x4.Scale(spawner.scale)
                });
                Ecb.AddComponent(chunkIndex, newEntity, new MoveComponent()
                {
                    position = spawner.position
                });
                //var rx = random.Next(0, 100);
                //var ry = random.Next(0, 100);
                //var rz = random.Next(0, 100);
                //Ecb.AddComponent(chunkIndex, newEntity, new MoveComponent()
                //{
                //    acceleration = 0.001f,
                //    maxSpeed = 0.01f,
                //    moveDirection = new float3(rx,ry,rz),
                //    moveSpeed = 0
                //});
                spawner.count--;
            }
        }
    }
}
